---
--类名: SecretManager.lua
--创建日期: 2018-6-15
--创建人: 宋建邦
--功能描述: 

local WinView = import(".SecretResultWinView")
local RewardView = import(".SecretRewardView")
local NewActivityDungeonsFailView = require("app.activityDungeons.views.NewActivityDungeonsFailView")
local PvpLevelView = require("app.pvp.views.PvpLevelView")
local SecretManager = class("SecretManager")
local SecretLevelUpView = import(".SecretLevelUpView")
local BoxItemVo = require("app.reward.models.BoxItemVo")

SecretManager.EvtSecretInfoChange = "secret_info_change"
SecretManager.EvtSecretActiveNextLayer = "secret_active_next_layer"
SecretManager.EvtSecretLevelUp = "secret_levelup"

function SecretManager:ctor()
end

SecretManager.maxLayer = 9
SecretManager.maxLevel = 9

SecretManager.ErrMsg = "ErrSecretDungeonNewSeasonOpen"
SecretManager.ErrEvent = "ErrSecretDungeonNewSeasonOpenEvent"
SecretManager.LSKey = "secretLevelUp"
function SecretManager:init()
    self:reqestSecretInfo()
    app.session:on("pb_secretDungeon.S2C_SecretDungeonResult",function(ret)
        -- dump( ret, " ------------------->>>> S2C_SecretDungeonResult" )
        self:reqestSecretInfo()

        if ret.isSuccess then
            self:showWinView(ret)
        else 
            self:showFailView(ret)
        end
    end)
    
    app.session:on("pb_secretDungeon.S2C_SecretDungeonTaskInfoNotify",function(ret)
        -- dump(ret, "taskinfochange:")
        -- if self.info then
        --     self.info.tasks = ret.tasks
        --     EM:notify(SecretManager.EvtSecretInfoChange)
        -- end
    end)

    EM:on(SecretManager.ErrEvent, function()
        UIHandler:getSystemUi():removeSystemUiByKey("m_secretController")
        app:sendMsg("NewDungeonTypeController", "openView" )
    end)

    local layerLv = 0
    local layercfg = nil
    repeat
        layerLv = layerLv + 1
        layercfg = GD:getDungeonSecretModeConfigById(layerLv)
    until(layercfg == nil)
    self.maxConfigLayer = layerLv - 1

    -- print("max level is :", self.maxConfigLayer)
end

function SecretManager:showFailView(ret)
    local view = NewActivityDungeonsFailView.new()
    view:onCloseView(function(sender)
		view:hide()
        UIHandler:removePopupUiByKey(sender:getViewName())
	end)

    local curScore = checknumber(ret.finishSeconds)
    local arg = {
        id = 301,
        type = 6,
        need = self:getGradesFromLayer(self.info.layer)[1].hmstr..string.format(" (%s)", L("copper_cup")),
        score = self:second2msStr(curScore)..L("lua_code_text_423"),
    }

    local ispassed = false
    local tls = string.split(GD:getDungeonSecretModeConfigById(self.info.layer).timeline, "|")
    for i, v in ipairs(tls) do
        if curScore < checknumber(v) then
            ispassed = true
            if i == 1 then
                arg.need = self:getGradesFromLayer(self.info.layer)[2].hmstr..string.format(" (%s)", L("silver_cup"))
            elseif i == 2 then
                arg.need = self:getGradesFromLayer(self.info.layer)[3].hmstr..string.format(" (%s)", L("gold_cup"))
            end            
        end
    end
    if ispassed then
        arg.title2 = L("lua_code_text_165")
        arg.score = self:second2msStr(curScore)
    end
    
	view:refreshSecretContent(arg)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end

function SecretManager:showWinView(ret)
    local view = WinView.new()
	view:onCloseView(function(sender)
		view:hide()
        UIHandler:removePopupUiByKey(sender:getViewName())
	end)

	view:refresh(ret)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end

function SecretManager:showLevelUpView(msg)
    local view = PvpLevelView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)

    -- local msg = self.info
    local arg = {
        title1 = L("lua_code_text_463"),
        title2 = string.format(L("lua_code_text_115"), tostring(msg.lv)),
        lv = msg.lv,
        tips1 = L("lua_code_text_94"),
        tips2 = string.format(L("lua_code_text_530"), tostring(msg.lv)),
    }
    view:refreshSecret(arg)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function SecretManager:showLayerUpView(msg)
    local view = SecretLevelUpView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)

    -- local msg = self.info
    local arg = {
        title1 = L("lua_code_text_231"),
        lv = msg.layer,
        tips2 = string.format(L("lua_code_text_268"), tostring(msg.layer)),
    }
    -- view:refreshSecret(arg)
    view:refresh(arg)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

--领奖
-- function SecretManager:showRewardView(dropLists)
--     local view = RewardView.new()
--     view:onCloseView(function()
--         self:reqestSecretInfo()
--         UIHandler:removePopupUiByKey(view:getViewName())
--     end)
--     UIHandler:addPopupUi(view, view:getViewName())
--     view:show()
--     view:showData(dropLists)
-- end

-- 判断秘境副本是否开启（和当前秘境副本的dungeonSubId相同）
function SecretManager:isTeamTargetOpen(teamTarget)
    return self.info and self.info.dungeonSubId == teamTarget:getDungeonSubId()
end

function SecretManager:reqestSecretInfo()
    app.session:request("pb_secretDungeon.C2S_SecretDungeonInfo", {}, function(msg)
        if self.info then
            if msg.lv > self.info.lv then
                -- EM:notify(SecretManager.EvtSecretLevelUp)
                app:saveValue(SecretManager.LSKey, true)
            end
            if msg.layer > self.info.layer then
                self:showLayerUpView(msg)
            end
        end
        self.info = msg
        -- dump(msg, "C2S_SecretDungeonInfo => ")
        if self.info and self.info.tasks and #self.info.tasks > 0 then
            table.sort(self.info.tasks, function(a, b)
                return a.needProgress < b.needProgress
            end)
        end

        EM:notify(SecretManager.EvtSecretInfoChange)
    end, nil, function(errMsg)
    end)
end

function SecretManager:reqestActiveNextLayer()
    app.session:request("pb_secretDungeon.C2S_SecretDungeonActiveNextLayer", {}, function(msg)
        -- dump(msg, "active next rsp:")
        self:reqestSecretInfo()
        -- self.info = msg

        EM:notify(SecretManager.EvtSecretActiveNextLayer)
    end, nil, function(errMsg)
    end) 
end

function SecretManager:reqestGetReward()
    app.session:request("pb_secretDungeon.C2S_SecretDungeonGetSeasonReward", {}, function(msg)
        -- self.info = msg
        -- dump(msg, "get reward:")

        -- EM:notify(SecretManager.EvtSecretInfoChange)
        if msg.OK then
            local items = {0,0,0,0,0}
            for i = 1, 5 do -- v in ipairs(msg.luckItems) do
                items[i] = BoxItemVo.new(msg.luckItems[i] or msg.luckItems[1])
            end
            
            items = table.randomCnt(items)
            app:sendMsg("BoxController", "onOpenBox", items)
            self:reqestSecretInfo()
        end
        
    end, nil, function(errMsg)
    end)
end

function SecretManager:second2msStr(aSec)
    local t = checknumber(aSec)
    local m = math.floor(t/60)
    local s = math.fmod(t, 60)

    return string.format("%d:%02d", m, s)
end

function SecretManager:reqGetTaskReward(aIndex)
    -- print("task index", aIndex)
    app.session:request("pb_secretDungeon.C2S_SecretDungeonGetTaskReward", {index = aIndex}, function(msg)
        -- self.info = msg
        -- dump(msg, "get task reward:")

        if msg.OK then
            local items = {0,0,0,0,0}
            for i = 1, 5 do -- v in ipairs(msg.luckItems) do
                items[i] = BoxItemVo.new(msg.luckItems[i] or msg.luckItems[1])
            end
            items = table.randomCnt(items)
            app:sendMsg("BoxController", "onOpenBox", items)
            self:reqestSecretInfo()
        end
        
    end, nil, function(errMsg)
    end)
end

function SecretManager:getCurrentExpRewards()
    self.secretConfig = GD:getDungeonSecretModeConfigById(self.info.layer)
    local exps = string.split(self.secretConfig.rewardExp, "|")
    local ret = {0, 0, 0}
    for i = 1, 3 do 
        ret[i] = checknumber(exps[i])
    end
    return ret 
end

-- 获取当前层战斗力的万分比修正值
function SecretManager:getCurrentPowerRevise()
    local secretConfig = GD:getDungeonSecretModeConfigById(self.info.layer)
    if secretConfig then
        return checknumber(secretConfig.powerRevise)
    end
    return 10000
end

function SecretManager:getGradesFromLayer(aLayer)
    self.secretConfig = GD:getDungeonSecretModeConfigById(aLayer)
    local rets = {{},{},{}}
    if not self.secretConfig then
        print("no secret mode config, id:", aLayer)
        return
    end

    local tls = string.split(self.secretConfig.timeline, "|")
    local exps = string.split(self.secretConfig.rewardExp, "|")

    rets[1].title = L("lua_code_text_288")
    rets[2].title = L("lua_code_text_228")
    rets[3].title = L("lua_code_text_462")

    for i = 1, 3 do 
        rets[i].hmstr = self:second2msStr(tls[i])
        rets[i].str = exps[i]
    end

    return rets
end

function SecretManager:getCurrentCopyName()
    if self.info then
        local cfg = GD:queryTeamTargetById(self.info.dungeonSubId)
        if cfg then
            return L(cfg.name)
        end
    end
    
    return "temp name"
end

function SecretManager:getCurrentSecretTaskIndex()
    if self.info and self.info.tasks and #self.info.tasks > 0 then
        for i, v in ipairs(self.info.tasks) do
            if checkbool(v.getReward) == false then
                return i - 1
            end
        end
    end
end

function SecretManager:hasSecretTaskReward()
    if self.info and self.info.tasks and #self.info.tasks > 0 then
        for i, v in ipairs(self.info.tasks) do
            if checkbool(v.getReward) == false and v.nowProgress >= v.needProgress then
                return true
            end
        end
    end

    return false
end

function SecretManager:getCurrentSecretTask()
    if self.info and self.info.tasks and #self.info.tasks > 0 then
        for i, v in ipairs(self.info.tasks) do
            if checkbool(v.getReward) == false then
                return v 
            end
        end
    end

    return nil
end

return SecretManager